package paper.parse;

import paper.parse.Author;
import java.util.Vector;
import java.util.Iterator;

public class AuthorList {
    Vector<Author> list = new Vector<Author>();

    public AuthorList() {
    }
    
    public void addAuthor(Author newAuthor, int sequence, double prob) {
        for (Iterator<Author> i = list.iterator(); i.hasNext();) {
            Author x = i.next();
            if (x.equals(newAuthor)) {
//                System.out.println(" " + x + " equals " + newAuthor);
                x.addProbability(prob);
                x.addSequence(sequence,prob);
                return;
            }
            if (x.isPrefixOf(newAuthor)) {
//                System.out.println(" " + x + " is prefix of " + newAuthor);
                x.addProbability(prob*0.125);
                x.addSequence(sequence,prob*0.125);
            }
            if (newAuthor.isPrefixOf(x)) {
                newAuthor.addProbability(prob*0.125); // fixme, this is wrong.
                newAuthor.addWholeSequence(x);        // not all of those probs
            }                                         // should be added here.
        }
//        System.out.println("NEW " + newAuthor);
        newAuthor.addProbability(prob);
        newAuthor.addSequence(sequence,prob);
        list.add(newAuthor); // not in list of authors yet.
    }

    public Vector<Author> findBest() {
        Vector<Author> best = new Vector<Author>();
        int cnt = 0;
        while (true) {
            double max = 0;
            Author bestMatch = null;
            for (Iterator<Author> i = list.iterator(); i.hasNext();) {
                Author x = i.next();
                if (cnt < x.sequenceProb.size()) {
                    Double prob = x.sequenceProb.get(cnt);
                    if (prob != null && prob > max) {
                        max = prob;
                        bestMatch = x;
                    }
                }
            }
            if (bestMatch == null) {
                break;
            }
            best.add(bestMatch);
            list.remove(bestMatch);
            cnt++;
        }
        if (cnt == 0) {
            return null;
        } else {
            return best;
        }
    }

    public String toString() {
        String r = "";
        for (Iterator<Author> i = list.iterator(); i.hasNext();) {
            Author x = i.next();
            r += "\n" + x;
        }
        return r;
    }

}
